package com.yuandengta.yomall.order.listener;

import com.rabbitmq.client.Channel;
import com.yuandengta.common.to.mq.SeckillOrderTO;
import com.yuandengta.yomall.order.constant.RabbitConstant;
import com.yuandengta.yomall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 秒杀订单 {@link OrderSeckillListener}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@RabbitListener(queues = RabbitConstant.ORDER_SECKILL_ORDER_QUEUE)
@Slf4j
@Service
public class OrderSeckillListener {

    @Autowired
    private OrderService orderService;

    /**
     * 创建秒杀订单
     * @param seckillOrder
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handlerSeckillOrder(SeckillOrderTO seckillOrder, Message message, Channel channel) {
        log.info("准备创建秒杀订单...");
        try {
            orderService.createSeckillOrder(seckillOrder);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
